#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
using namespace std;
#include <sys/types.h>
#include <unistd.h>

using task_t = function<void()>;

void DownLoad()
{
    cout << "我是下载任务..., pid: " << getpid() << endl;
}

void Log()
{
    cout << "我是日制任务..., pid: " << getpid() << endl;
}

void Sql()
{
    cout << "我是数据任务..." << getpid() << endl;
}

static int number = 0;
class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }

    void InsertTask(task_t t)
    {
        tasks[number++] = t;
    }

    void Excute(int number)
    {
        if (tasks.find(number) == tasks.end())
            return;
        tasks[number]();
    }

    int SelectTask()
    {
        return rand() % number;
    }
    ~TaskManger()
    {
    }

private:
    unordered_map<int, task_t> tasks;
};

TaskManger tm;

void Worker()
{
    // dup2重定向,直接从0读
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if (n == 0)
        {
            cout << "pid: " << getpid() << "quit..." << endl;
            break;
        }
        else
        {
        }
    }
}